package com.cy.sp02.controller;

import com.cy.sp01.pojo.Item;
import com.cy.sp01.service.ItemService;
import com.cy.web.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@CrossOrigin
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;

    //获取订单的商品列表
    /**
     *
     * @param orderId
     * @return JsonResult 用来封装返回给客户端的数据
     *          - code 状态码     0
     *          - msg  提示消息   null
     *          - data 数据对象   List<Item>
     *   "{"code":0,"msg":"null","data":[{},{},{}]}"
     */
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        List<Item> items = itemService.getItems(orderId);
        JsonResult result = JsonResult.ok().data(items);
        //随机的延迟代码
        //90%概率会执行延迟代码
        if(Math.random()<0.9){
            //随机延迟时常，0到5秒
            int t = new Random().nextInt(5000);
            log.info("随机延迟时常："+t);
            Thread.sleep(t);
        }
        return result;
    }

    //减少商品库存

    /**
     *
     * @param items @RequestBody 接收客户端体骄傲的参数 完整的接收HTTP协议体数据，再转成Java对象
     * @return
     */
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("商品减少库存成功");
    }


}
